package com.example.backend.service;

import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.enums.TicketStatus;
import com.example.backend.repository.TicketRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 定时任务服务
 * 处理系统定时任务
 */
@Service
public class ScheduledTaskService {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledTaskService.class);

    @Autowired
    private TicketRepository ticketRepository;

    @Autowired
    private EmailService emailService;

    /**
     * 每小时检查超时工单
     */
    @Scheduled(fixedRate = 3600000) // 1小时
    @Transactional(readOnly = true)
    public void checkOverdueTickets() {
        logger.info("开始检查超时工单...");
        
        try {
            // 查找超过24小时未处理的OPEN状态工单
            Instant cutoffTime = Instant.now().minus(24, ChronoUnit.HOURS);
            List<Ticket> overdueTickets = ticketRepository.findOverdueTickets(cutoffTime, TicketStatus.OPEN, org.springframework.data.domain.Pageable.unpaged()).getContent();
            
            if (!overdueTickets.isEmpty()) {
                logger.warn("发现 {} 个超时工单", overdueTickets.size());
                
                for (Ticket ticket : overdueTickets) {
                    // 发送超时提醒邮件
                    if (ticket.getAssignedTo() != null && ticket.getAssignedTo().getEmail() != null) {
                        emailService.sendTicketNotification(
                            ticket.getAssignedTo().getEmail(),
                            "TK" + ticket.getId(),
                            ticket.getTitle(),
                            "超时提醒"
                        );
                    }
                }
            }
            
            logger.info("超时工单检查完成");
        } catch (Exception e) {
            logger.error("检查超时工单时发生错误", e);
        }
    }

    /**
     * 每天凌晨2点清理过期数据
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanupExpiredData() {
        logger.info("开始清理过期数据...");
        
        try {
            // 这里可以添加清理过期日志、临时文件等逻辑
            // 例如：清理30天前的系统日志
            
            logger.info("过期数据清理完成");
        } catch (Exception e) {
            logger.error("清理过期数据时发生错误", e);
        }
    }

    /**
     * 每天上午9点发送日报
     */
    @Scheduled(cron = "0 0 9 * * ?")
    public void sendDailyReport() {
        logger.info("开始生成日报...");
        
        try {
            // 统计昨天的工单数据
            Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS);
            long totalTickets = ticketRepository.countByCreatedAtAfter(yesterday);
            long resolvedTickets = ticketRepository.countByStatus(TicketStatus.RESOLVED);
            
            logger.info("昨日工单统计 - 总数: {}, 已解决: {}", totalTickets, resolvedTickets);
            
            // 这里可以发送日报邮件给管理员
            
            logger.info("日报生成完成");
        } catch (Exception e) {
            logger.error("生成日报时发生错误", e);
        }
    }
}
